package com.experienceBaby.Cashbook.adapter;


import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.experienceBaby.Cashbook.R;
import com.experienceBaby.Cashbook.bean.Item;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ItemAdapter extends BaseAdapter {
    private Context context;
    private List<Item> items;
    private Map<Integer, ViewHolder> viewHolderMap;

    private int select = -1;

    public int getSelect() {
        return select;
    }

    public void setSelect(int select) {
        this.select = select;
    }

    public ItemAdapter(Context context, List<Item> items) {
        this.context = context;
        this.items = items;
        viewHolderMap = new HashMap<>();
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Item getItem(int i) {
        return items.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder;
        if (null != view) {
            viewHolder = (ViewHolder) view.getTag();
        } else {
            viewHolder = new ViewHolder();
            view = LayoutInflater.from(context).inflate(R.layout.item_grid, viewGroup, false);
            viewHolder.iv = view.findViewById(R.id.img_icon);
            viewHolder.tv = view.findViewById(R.id.txt_icon);
            viewHolder.ll = view.findViewById(R.id.item_ll);

            view.setTag(viewHolder);
            if (viewHolderMap.get(i) == null) {
                viewHolderMap.put(i, viewHolder);
            }

            viewHolder.ll.setOnClickListener(view1 -> {
                for (int j = 0; j < getCount(); j++) {
                    getItem(j).setSelect(false);
                    Glide
                            .with(context)
                            .load(getItem(j).getImage())
                            .into(viewHolderMap.get(j).iv);
                }
                select = i;
                getItem(i).setSelect(true);
                Glide
                        .with(context)
                        .load(getItem(i).getSelect())
                        .into(viewHolder.iv);
            });
            viewHolder.tv.setText(items.get(i).getText());
            Glide
                    .with(context)
                    .load(getItem(i).getImage())
                    .into(viewHolder.iv);
        }
        return view;
    }


    class ViewHolder {
        private ImageView iv;
        private TextView tv;
        private RelativeLayout ll;
    }
}
